package com.kt.learn1

/**
 * Kotlin 异常处理示例
 * 包括 try-catch-finally、抛出异常、自定义异常等
 */

fun main() {
    // 基本异常处理
    chapter1BasicExceptionHandling()

    // 多个 catch 块
    chapter2MultipleCatchBlocks()

    // finally 块
    chapter3FinallyBlock()

    // try 作为表达式
    chapter4TryAsExpression()

    // 抛出异常
    chapter5ThrowingExceptions()

    // 自定义异常
    chapter6CustomExceptions()
}

// 基本异常处理
fun chapter1BasicExceptionHandling() {
    println("\n===== 基本异常处理 =====")

    try {
        val result = 10 / 0
        println("Result: $result")
    } catch (e: ArithmeticException) {
        println("ArithmeticException caught: ${e.message}")
    }
}

// 多个 catch 块
fun chapter2MultipleCatchBlocks() {
    println("\n===== 多个 catch 块 =====")

    try {
        val array = arrayOf(1, 2, 3)
        println("Element at index 5: ${array[5]}")
    } catch (e: ArithmeticException) {
        println("ArithmeticException caught: ${e.message}")
    } catch (e: ArrayIndexOutOfBoundsException) {
        println("ArrayIndexOutOfBoundsException caught: ${e.message}")
    } catch (e: Exception) {
        println("General Exception caught: ${e.message}")
    }
}

// finally 块
fun chapter3FinallyBlock() {
    println("\n===== finally 块 =====")

    try {
        val result = 10 / 2
        println("Result: $result")
    } catch (e: ArithmeticException) {
        println("ArithmeticException caught: ${e.message}")
    } finally {
        println("Finally block executed")
    }
}

// try 作为表达式
fun chapter4TryAsExpression() {
    println("\n===== try 作为表达式 =====")

    val result = try {
        10 / 2
    } catch (e: ArithmeticException) {
        -1
    }

    println("Result: $result")
}

// 抛出异常
fun chapter5ThrowingExceptions() {
    println("\n===== 抛出异常 =====")

    fun checkAge(age: Int) {
        if (age < 0) {
            throw IllegalArgumentException("Age cannot be negative")
        }
        println("Age is valid: $age")
    }

    try {
        checkAge(-5)
    } catch (e: IllegalArgumentException) {
        println("Exception caught: ${e.message}")
    }
}

// 自定义异常
fun chapter6CustomExceptions() {
    println("\n===== 自定义异常 =====")

    // 定义一个自定义异常类
    class InvalidEmailException(message: String) : Exception(message)

    fun validateEmail(email: String) {
        if (!email.contains("@")) {
            throw InvalidEmailException("Invalid email address")
        }
        println("Email is valid: $email")
    }

    try {
        validateEmail("user.example.com")
    } catch (e: InvalidEmailException) {
        println("Exception caught: ${e.message}")
    }
}